package cn.tmpan.project.interceptor;

import cn.tmpan.project.common.ServerResponse;
import cn.tmpan.project.common.enums.ResponseCode;
import cn.tmpan.project.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * The type Login interceptor.
 *
 * @Author tieMinPan
 * @Desc: Description
 * @Date 2019 -01-24 15:30
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        /**
         *@desc 登录校验逻辑  这里默认true 实际开发需修改自己业务逻辑
         */
        if (true) {
            PrintWriter writer = null;
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;  charset=UTF-8");
            try {
                writer = response.getWriter();
                ServerResponse serverResponse = ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
                writer.print(JsonUtil.objToString(serverResponse));
                return false;

            } catch (IOException e) {
                log.error("登录拦截IO异常:{}", e.getMessage());
            } finally {
                if (writer != null) {
                    writer.close();
                }
            }

        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }
}
